package managedbean;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;

import model.Author;
import dao.AuthorDao;

@ManagedBean(name="authorBean")
@SessionScoped
public class AuthorManagedBean {

	private List<Author> authors;
	private Author selectedAuthor;

	@ManagedProperty(value="#{authorDao}")
	private AuthorDao authorDao;

	public AuthorDao getAuthorDao() {
		return authorDao;
	}
	
	public void setAuthorDao(AuthorDao authorDao) {
		this.authorDao = authorDao;
	}
	
	public List<Author> getAuthors() {
		return authors;	
	}

	public void setAuthors(List<Author> authors) {
		this.authors = authors;
	}

	public Author getSelectedAuthor() {
		return selectedAuthor;
	}

	public void setSelectedAuthor(Author selectedAuthor) {
		this.selectedAuthor = selectedAuthor;
	}
	
	public Author getAuthorById(Long id) {
		for (Author author : getAuthors()) {
			if (author.getId().equals(id)) {
				return author;
			}
		}
		return null;
	}
	
	@PostConstruct
	public void refreshAuthors() {
		setAuthors(getAuthorDao().searchAllAuthors());
	}
	
	public String addAction() {
		setSelectedAuthor(new Author());
		return "author";
	}
	
	public String quitAction() {
		setSelectedAuthor(null);
		return "listauthor";
	}
	
	public String save() {
		getAuthorDao().persist(getSelectedAuthor());
		getAuthors().add(getSelectedAuthor());
		refreshAuthors();
		return "listauthor";
	}
	
	public String merge() {
		getAuthorDao().merge(getSelectedAuthor());
		setSelectedAuthor(null);
		return "listauthor";
	}
	
	public String delete() {
		getAuthorDao().remove(getSelectedAuthor());
		setSelectedAuthor(null);
		refreshAuthors();
		return "listauthor";
	}
}
